using Tycho.Parser.Tokens;

namespace Tycho.Parser.Peg {
    public class DelimitedRule<Context> : Rule<Context> {
        private readonly Rule<Context> Delimiter;
        private readonly Rule<Context> Item;

        public DelimitedRule (Rule<Context> item, Rule<Context> delimiterRule) {
            Item = item;
            Delimiter = delimiterRule;
        }

        protected override RuleParseResult<Context> ReallyParse (Token[] tokens, int index, Context context) {
            RuleParseResult<Context> itemResult = Item.Parse (tokens, index, context);
            if (itemResult != null) {
                while (true) {
                    RuleParseResult<Context> delimiterResult = Delimiter.Parse (tokens, itemResult.Index, itemResult.Context);

                    if (delimiterResult == null) {
                        return itemResult;
                    }

                    delimiterResult.MergeCapturesFrom (itemResult);

                    RuleParseResult<Context> nextItemResult = Item.Parse (tokens, delimiterResult.Index, delimiterResult.Context);

                    if (nextItemResult == null) {
                        return itemResult;
                    } else {
                        nextItemResult.MergeCapturesFrom (delimiterResult);
                        itemResult = nextItemResult;
                    }
                }
            } else {
                return null;
            }
        }
    }
}